import React from 'react';
import PropTypes from 'prop-types';
import { Layout, Icon, message } from 'antd';
import DocumentTitle from 'react-document-title';
import { connect } from 'dva';
import { Route, Redirect, Switch, routerRedux } from 'dva/router';
import { ContainerQuery } from 'react-container-query';
import classNames from 'classnames';
import { enquireScreen } from 'enquire-js';
import GlobalHeader from '../components/GlobalHeader';
import GlobalFooter from '../components/GlobalFooter';
import SiderMenu from '../components/SiderMenu';
import SiderSubMenu from '../components/SiderSubMenu';
import NotFound from '../routes/Exception/404';
import { getRoutes } from '../utils/utils';
import Authorized from '../utils/Authorized';
import { getMenuData } from '../common/menu';
import logo from '../assets/logo_pic.png';
import { getRole } from '../utils/authority'
const { Content } = Layout;
const { AuthorizedRoute } = Authorized;

/**
 * 根据菜单取得重定向地址.
 */
const redirectData = [];
const getRedirect = (item) => {
  if (item && item.children) {
    if (item.children[0] && item.children[0].path) {
      redirectData.push({
        from: `/${item.path}`,
        to: `/${item.children[0].path}`,
      });
      item.children.forEach((children) => {
        getRedirect(children);
      });
    }
  }
};
getMenuData().forEach(getRedirect);

const query = {
  'screen-xs': {
    maxWidth: 575,
  },
  'screen-sm': {
    minWidth: 576,
    maxWidth: 767,
  },
  'screen-md': {
    minWidth: 768,
    maxWidth: 991,
  },
  'screen-lg': {
    minWidth: 992,
    maxWidth: 1199,
  },
  'screen-xl': {
    minWidth: 1200,
  },
};

let isMobile;
enquireScreen((b) => {
  isMobile = b;
});

class BasicLayout extends React.PureComponent {
  static childContextTypes = {
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object,
  }
  state = {
    isMobile,
  };
  getChildContext() {
    const { location, routerData } = this.props;
    return {
      location,
      breadcrumbNameMap: routerData,
    };
  }

  interval;

  componentDidMount() {
    enquireScreen((mobile) => {
      this.setState({
        isMobile: mobile,
      });
    });

    this.props.dispatch({
      type: 'user/fetchCurrent',
    });

    this.props.dispatch({
      type: 'global/fetchNotices',
    });

    this.interval = setInterval(this.searchNotice, 1000);
  }

  searchNotice = () => {
    // console.log("featch notices");
  }

  componentWillUnmount() {
    // clearInterval(this.interval);
  }

  getPageTitle() {
    const { routerData, location } = this.props;
    const { pathname } = location;
    let title = 'sdfz';
    if (routerData[pathname] && routerData[pathname].name) {
      title = `${routerData[pathname].name} - sdfz`;
    }
    return title;
  }

  getBashRedirect = () => {
    // According to the url parameter to redirect
    // 这里是重定向的,重定向到 url 的 redirect 参数所示地址
    const urlParams = new URL(window.location.href);

    const redirect = urlParams.searchParams.get('redirect');
    // Remove the parameters in the url

    if (redirect) {
      urlParams.searchParams.delete('redirect');
      window.history.replaceState(null, 'redirect', urlParams.href);
    }

    if (!redirect || redirect.indexOf('/homePage') >= 0) {
      return '/homePage';
    }

    return redirect;
  }


  handleMenuCollapse = (collapsed) => {
    this.props.dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
  }

  handleNoticeClear = (type) => {
    // message.success(`${type}已清空`);
    // this.props.dispatch({
    //   type: 'global/clearNotices',
    //   payload: type,
    // });
    this.props.dispatch(routerRedux.push('/noticeManagement/innerMessage/unread'));
    this.setState({ popupVisible: false });
  }

  handleMenuClick = ({ key }) => {
    if (key === 'triggerError') {
      this.props.dispatch(routerRedux.push('/exception/trigger'));
      return;
    }

    if (key === 'logout') {
      this.props.dispatch({
        type: 'login/logout',
      });
    }

    if (key === 'user') {
      this.props.dispatch(routerRedux.push({
        pathname: '/userCenter',
      }));
    }
  }

  handleNoticeVisibleChange = (visible) => {
    this.setState({ popupVisible: visible });
    if (visible) {
      this.props.dispatch({
        type: 'global/fetchNotices',
      });
    }
  }

  handleItemClick = (item, tabProps) => {
    this.props.dispatch(routerRedux.push({
      pathname: '/noticeManagement/innerMessage/allView/' + item.id,
      query: { noticeItemId: item.id },
    }));
    this.setState({ popupVisible: false });
  }


  onMenuSubMenuClick = ({ key }) => {

    const menuData = getMenuData();
    const currMenu = menuData.filter(data => data.path == key)[0];

    this.props.dispatch({
      type: 'global/changeCurrMenu',
      payload: currMenu,
    });
  }

  render() {
    const {
      currentUser, collapsed, fetchingNotices, notices, noticeCount, routerData, match, location, currMenu,
    } = this.props;

    const bashRedirect = this.getBashRedirect();
    const layout = (
      <Layout>
        <SiderMenu
          logo={logo}
          // 不带Authorized参数的情况下如果没有权限,会强制跳到403界面
          // If you do not have the Authorized parameter
          // you will be forced to jump to the 403 interface without permission
          Authorized={Authorized}
          menuData={getMenuData()}
          collapsed={collapsed}
          location={location}
          isMobile={this.state.isMobile}
          onCollapse={this.handleMenuCollapse}
          notices={notices}
          noticeCount={noticeCount}
          onSubMenuClick={this.onMenuSubMenuClick}
          currMenu={currMenu}
        />
        <Layout style={{ flexDirection: 'column' }}>
          <GlobalHeader
            logo={logo}
            currentUser={currentUser}
            fetchingNotices={fetchingNotices}
            notices={notices}
            noticeCount={noticeCount}
            collapsed={collapsed}
            isMobile={this.state.isMobile}
            onCollapse={this.handleMenuCollapse}
            onMenuClick={this.handleMenuClick}
            onNoticeVisibleChange={this.handleNoticeVisibleChange}
            onNoticeClear={this.handleNoticeClear}
            popupVisible={this.state.popupVisible}
            handleItemClick={this.handleItemClick}
          />


          <div style={{ display: 'flex', flexDirection: 'row', overflow:'auto' }}>
            {
              !collapsed && currMenu && (
                <SiderSubMenu
                  // logo={logo}
                  // 不带Authorized参数的情况下如果没有权限,会强制跳到403界面
                  // If you do not have the Authorized parameter
                  // you will be forced to jump to the 403 interface without permission
                  Authorized={Authorized}
                  menuData={currMenu.children}
                  menuName={currMenu.name}
                  collapsed={currMenu.children ? false : true}
                  location={location}
                  isMobile={this.state.isMobile}
                  onCollapse={this.handleMenuCollapse}
                  notices={notices}
                  noticeCount={noticeCount}
                />

              )
            }


            <Content style={{ margin: '24px 24px 0', height: '100%' }}>
              <div style={{ minHeight: 'calc(100vh - 260px)' }}>
                <Switch>
                  {
                    redirectData.map(item =>
                      <Redirect key={item.from} exact from={item.from} to={item.to} />
                    )
                  }
                  {
                    getRoutes(match.path, routerData).map(item =>
                      (
                        <AuthorizedRoute
                          key={item.key}
                          path={item.path}
                          component={item.component}
                          exact={item.exact}
                          authority={item.authority}
                          redirectPath="/exception/403"
                        />
                      )
                    )
                  }
                  <Redirect exact from="/" to={bashRedirect} />
                  <Route render={NotFound} />
                </Switch>
              </div>
              <GlobalFooter
                links={[
                  // {
                  //   key: 'Pro 首页',
                  //   title: 'Pro 首页',
                  //   // href: 'http://pro.ant.design',
                  //   blankTarget: true,
                  // }, {
                  //   key: 'github',
                  //   title: <Icon type="github" />,
                  //   // href: 'https://github.com/ant-design/ant-design-pro',
                  //   blankTarget: true,
                  // }, {
                  //   key: 'Ant Design',
                  //   title: 'Ant Design',
                  //   // href: 'http://ant.design',
                  //   blankTarget: true,
                  // }
                ]}
                copyright={
                  <div>
                    Copyright <Icon type="copyright" /> 2018 sdfz 技术团队出品
                </div>
                }
              />
            </Content>
          </div>
        </Layout>
      </Layout>
    );

    return (
      <DocumentTitle title={this.getPageTitle()}>
        <ContainerQuery query={query}>
          {params => <div className={classNames(params)}>{layout}</div>}
        </ContainerQuery>
      </DocumentTitle>
    );
  }
}

export default connect(({ user, global, loading }) => ({
  currentUser: user.currentUser,
  collapsed: global.collapsed,
  fetchingNotices: loading.effects['global/fetchNotices'],
  notices: global.notices,
  noticeCount: global.noticeCount,
  currMenu: global.currMenu,
}))(BasicLayout);
